// 认证服务，管理用户登录状态

// 模拟用户数据
const mockUser = {
  username: 'admin',
  password: 'password',
  name: '管理员',
  avatar: 'https://picsum.photos/200/200'
};

class AuthService {
  constructor() {
    this.user = null;
    this.isAuthenticated = false;
    this.loadUserFromStorage();
  }

  // 从localStorage加载用户信息
  loadUserFromStorage() {
    const user = localStorage.getItem('user');
    if (user) {
      this.user = JSON.parse(user);
      this.isAuthenticated = true;
    }
  }

  // 保存用户信息到localStorage
  saveUserToStorage(user) {
    localStorage.setItem('user', JSON.stringify(user));
  }

  // 移除用户信息
  removeUserFromStorage() {
    localStorage.removeItem('user');
  }

  // 登录方法
  login(username, password) {
    return new Promise((resolve, reject) => {
      // 模拟API请求延迟
      setTimeout(() => {
        if (username === mockUser.username && password === mockUser.password) {
          this.user = {
            username: mockUser.username,
            name: mockUser.name,
            avatar: mockUser.avatar
          };
          this.isAuthenticated = true;
          this.saveUserToStorage(this.user);
          resolve(this.user);
        } else {
          reject(new Error('用户名或密码错误'));
        }
      }, 500);
    });
  }

  // 登出方法
  logout() {
    this.user = null;
    this.isAuthenticated = false;
    this.removeUserFromStorage();
  }

  // 获取当前用户
  getCurrentUser() {
    return this.user;
  }

  // 检查是否已认证
  checkAuth() {
    return this.isAuthenticated;
  }
}

// 创建单例实例
export default new AuthService();